
let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');
    
/**
 * 查询档案数据 2018-10-18
 *
 * 按条件查询档案数据
 *
 */
router.get('/:code/basearchives', function (req, res, next) {
    let params = req.query;
    let role = req.session.role;
    var limits = "";
    var sql = "";
    var datas = [];

    if (req.params.code === undefined || req.params.code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    let isDelete = 0;
    if (params.isDelete !== undefined && params.isDelete !== "") {
        isDelete = 1;
    }

    sql = " where isDelete = ?";
    datas.push(isDelete);

    if (params.year !== undefined && params.year !== "") {
        sql += " and year = ?";
        datas.push(params.year);
    }

    if (params.classifyCode !== undefined && params.classifyCode !== "") {
        sql += " and classifyCode = ?";
        datas.push(params.classifyCode);
    }

    if (params.departmentName !== undefined && params.departmentName !== "") {
        sql += " and departmentName = ?";
        datas.push(params.departmentName);
    }

    if (params.title !== undefined && params.title !== "") {
        sql += " and title like ?";
        datas.push("%" + params.title + "%");
    }

    if (params.keyword !== undefined && params.keyword !== "") {
        let arr = params.keyword.split(/[, ]/);
        for (let i = 0; i < arr.length; i ++) {
            if (arr[i] !== '') {
                sql += " and keyword like ?";
                datas.push("%" + arr[i] + "%");
            }
        }
    }

    req.app.db.query("select count(1) as totalCount from s_" + req.params.code + " "  + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select id, code, fatherId, classifyCode, classifyName, year, departmentName, " +
            "classifyNo, volumeNo, fileNo, fileCode, title, subTitle, content, person1, person2, page, " +
            "DATE_FORMAT(beginDate,'%Y-%m-%d') as beginDate , DATE_FORMAT(endDate,'%Y-%m-%d') as endDate, storagePeriod rank, carrier, text, recordType, keyword, " +
            "archived, archivesFrom, archivesTo, case when (archivesDate is null) then '' else DATE_FORMAT(archivesDate,'%Y-%m-%d') end  as archivesDate, isDelete, userId, userName, createDate, updateDate, " +
            "case when (archived = 1) then '是' else '否' end as archivedName from s_" + req.params.code + " "  + sql + " order by classifyNo " +  limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});


/**
 * 查看档案数据 2018-10-18
 *
 * 按id查看指定的档案信息
 *
 */
router.get('/:code/basearchives/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = params.code;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    let isDelete = 0;
    if (req.query.isDelete !== undefined && req.query.isDelete !== "") {
        isDelete = 1;
    }

    req.app.db.query("select * from s_" + code + " where id = ? and isDelete = ?", [params.id, isDelete], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

router.get('/:code/basearchives/:id/file', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = params.code;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    let isDelete = 0;
    if (req.query.isDelete !== undefined && req.query.isDelete !== "") {
        isDelete = 1;
    }

    req.app.db.query("select id, code, fatherId, classifyCode, classifyName, year, departmentName, classifyNo, volumeNo from s_" + code + " where id = ? and isDelete = ?", [params.id, isDelete], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        let file = results[0];
        file.fatherId = file.id;

        res.json({"success": true, "data": file});
    });
});

router.get('/:code/tree', function (req, res, next) {
    let params = req.params;
    let code = params.code;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    req.app.db.query("SELECT classifyCode, year, departmentName from s_" + code + " where isDelete = ? GROUP BY classifyCode, year, departmentName", [0], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "data": getClassifyTree(results)});
    });
});

function getClassifyTree(datas) {
    let r = [];

    for (let i = 0; i < datas.length; i ++) {
        let x1 = false;
        for (let j = 0; j < r.length; j ++) {
            if (datas[i].classifyCode === r[j].classifyCode) {
                let x2 = false;
                for (let m = 0; m < r[j].nodes.length; m ++) {
                    if (datas[i].year === r[j].nodes[m].year) {
                        let x3 = false;
                        for (let n = 0; n < r[j].nodes[m].nodes.length; n ++) {
                            if (datas[i].departmentName === r[j].nodes[m].nodes[n].departmentName) {
                                x3 = true;
                                break;
                            }
                        }

                        if (!x3) {
                            r[j].nodes[m].nodes.push(putDepartmentName(datas[i]));
                        }
                        x2 = true;
                        break;
                    }
                }

                if (!x2) {
                    r[j].nodes.push(putYear(datas[i]));
                }
                x1 = true;
                break;
            }
        }

        if (!x1) {
            r.push(putClassifyCode(datas[i]));
        }

    }

    return r;
}

function putClassifyCode(data) {
    let x3 = {"id": 0, "text": data.departmentName, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName};
    let x2 = {"id": 0, "text": data.year, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName, "selectable": false, "nodes": [x3]};
    let x1 = {"id": 0, "text": data.classifyCode, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName, "selectable": false, "nodes": [x2]};
    return x1;
}

function putYear(data) {
    let x3 = {"id": 0, "text": data.departmentName, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName};
    let x2 = {"id": 0, "text": data.year, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName, "selectable": false, "nodes": [x3]};
    return x2;
}

function putDepartmentName(data) {
    let x3 = {"id": 0, "text": data.departmentName, "classifyCode": data.classifyCode, "year": data.year, "departmentName": data.departmentName};
    return x3;
}

/**
 * 修改档案数据 2018-10-18
 *
 *
 */
router.put('/:code/basearchives/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let code = req.params.code;
    let fatherId = params.fatherId;

    if (params.id === undefined || params.id === "" || !(params.id > 0)) {
        res.json({"success": false, "message": "编码不正确！"});
        return;
    }

    req.app.db.query("select archived from s_" + code + " where id = ? and isDelete = ?", [params.id, 0], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "信息不存在，无法修改!"});
            return;
        }

        if (results[0].archived === 1) {
            res.json({"success": false, "message": "信息已归档，无法修改!"});
            return;
        }

        if (fatherId === undefined || fatherId === "" || !(fatherId >= 0)) {
            res.json({"success": false, "message": "档案编码不正确！"});
            return;
        }

        if (fatherId === 0) {
            let classifyCode;
            if (params.classifyCode !== undefined && params.classifyCode !== "") {
                classifyCode = params.classifyCode;
            }

            let year = 2000;
            if (params.year !== undefined || params.year !== "") {
                year = params.year;
            }

            if (params.departmentName === undefined || params.departmentName === '') {
                res.json({"success": false, "message": "部门不能为空！"});
                return;
            }

            let volumeNo = 0;
            if (params.volumeNo !== undefined || params.volumeNo !== "") {
                volumeNo = params.volumeNo;
            }

            let fileNo = 0;

            if (params.title === undefined || params.title === '') {
                res.json({"success": false, "message": "档案标题不能为空！"});
                return;
            }

            let page = 0;
            if (params.page !== undefined || params.page !== "") {
                page = params.page;
            }

            // if (params.beginDate === undefined || params.beginDate === '') {
            //     res.json({"success": false, "message": "档案开始时间不能为空！"});
            //     return;
            // }
            //
            // if (params.endDate === undefined || params.endDate === '') {
            //     res.json({"success": false, "message": "档案结束时间不能为空！"});
            //     return;
            // }

            let storagePeriod = 0;
            if (params.storagePeriod !== undefined || params.storagePeriod !== "") {
                storagePeriod = params.storagePeriod;
            }

            let rank = 0;
            if (params.rank !== undefined || params.rank !== "") {
                rank = params.rank;
            }

            let carrier = 0;
            if (params.carrier !== undefined || params.carrier !== "") {
                carrier = params.carrier;
            }

            let text = 0;
            if (params.text !== undefined || params.text !== "") {
                text = params.text;
            }

            let recordType = 0;
            if (params.recordType !== undefined || params.recordType !== "") {
                recordType = params.recordType;
            }

            let keyword = getKeyword(params.title);

            req.app.db.query("call proc_archives_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [code, 0, params.id, fatherId, classifyCode, year, params.departmentName, volumeNo, fileNo, '',
                    params.title, params.subTitle, params.content, params.person1, params.person2, page, params.beginDate, params.endDate,
                    storagePeriod, rank, carrier, text, recordType,
                    keyword, params.archivesFrom, params.archivesTo, user.id, user.trueName], function (err, results, fields) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    let result = results[0][0]._result;

                    res.json({"success": result === 1, "message": global.archivesMsg.add[result]});
                });
        }
        else {
            let fileNo = 1;
            if (params.fileNo !== undefined || params.fileNo !== "") {
                fileNo = params.fileNo;
            }

            if (params.title === undefined || params.title === '') {
                res.json({"success": false, "message": "档案标题不能为空！"});
                return;
            }

            let page = 0;
            if (params.page !== undefined || params.page !== "") {
                page = params.page;
            }

            // if (params.beginDate === undefined || params.beginDate === '') {
            //     res.json({"success": false, "message": "文件日期不能为空！"});
            //     return;
            // }

            let storagePeriod = 0;
            if (params.storagePeriod !== undefined || params.storagePeriod !== "") {
                storagePeriod = params.storagePeriod;
            }

            let rank = 0;
            if (params.rank !== undefined || params.rank !== "") {
                rank = params.rank;
            }

            let carrier = 0;
            if (params.carrier !== undefined || params.carrier !== "") {
                carrier = params.carrier;
            }

            let text = 0;
            if (params.text !== undefined || params.text !== "") {
                text = params.text;
            }

            let recordType = 0;
            if (params.recordType !== undefined || params.recordType !== "") {
                recordType = params.recordType;
            }

            let keyword = getKeyword(params.title);

            req.app.db.query("call proc_archives_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [code, 1, params.id, fatherId, 0, 0, '', 0, fileNo, params.fileCode,
                    params.title, params.subTitle, params.content, params.person1, params.person2, page, params.beginDate, null,
                    storagePeriod, rank, carrier, text, recordType,
                    keyword, params.archivesFrom, params.archivesTo, user.id, user.trueName], function (err, results, fields) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    let result = results[0][0]._result;

                    res.json({"success": result === 1, "message": global.archivesMsg.add[result]});
                });
        }
    });
});

/**
 * 新增档案、文件数据 2018-10-18
 *
 *
 */
router.post('/:code/basearchives/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let code = req.params.code;
    let fatherId = params.fatherId;

    if (fatherId === undefined || fatherId === "" || !(fatherId >= 0)) {
        res.json({"success": false, "message": "档案编码不正确！"});
        return;
    }

    if (fatherId === 0) {
        let classifyCode;
        if (params.classifyCode !== undefined && params.classifyCode !== "") {
            classifyCode = params.classifyCode;
        }

        let year = 2000;
        if (params.year !== undefined && params.year !== "") {
            year = params.year;
        }

        if (params.departmentName === undefined || params.departmentName === '') {
            res.json({"success": false, "message": "部门不能为空！"});
            return;
        }

        let volumeNo = 0;
        if (params.volumeNo !== undefined && params.volumeNo !== "") {
            volumeNo = params.volumeNo;
        }

        let fileNo = 0;

        if (params.title === undefined || params.title === '') {
            res.json({"success": false, "message": "档案标题不能为空！"});
            return;
        }

        let page = 0;
        if (params.page !== undefined && params.page !== "") {
            page = params.page;
        }

        // if (params.beginDate === undefined || params.beginDate == null || params.beginDate === '') {
        //     res.json({"success": false, "message": "档案开始时间不能为空！"});
        //     return;
        // }
        //
        // if (params.endDate === undefined || params.endDate == null || params.endDate === '') {
        //     res.json({"success": false, "message": "档案结束时间不能为空！"});
        //     return;
        // }

        let storagePeriod = 0;
        if (params.storagePeriod !== undefined || params.storagePeriod !== "") {
            storagePeriod = params.storagePeriod;
        }

        let rank = 0;
        if (params.rank !== undefined || params.rank !== "") {
            rank = params.rank;
        }

        let carrier = 0;
        if (params.carrier !== undefined || params.carrier !== "") {
            carrier = params.carrier;
        }

        let text = 0;
        if (params.text !== undefined || params.text !== "") {
            text = params.text;
        }

        let recordType = 0;
        if (params.recordType !== undefined || params.recordType !== "") {
            recordType = params.recordType;
        }

        let keyword = getKeyword(params.title);

        req.app.db.query("call proc_archives_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [code, 0, 0, fatherId, classifyCode, year, params.departmentName, volumeNo, fileNo, '',
                params.title, params.subTitle, params.content, params.person1, params.person2, page, params.beginDate, params.endDate,
                storagePeriod, rank, carrier, text, recordType,
                keyword, params.archivesFrom, params.archivesTo, user.id, user.trueName], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            let result = results[0][0]._result;

            res.json({"success": result === 1, "message": global.archivesMsg.add[result]});
        });
    }
    else {
        let fileNo = 1;
        if (params.fileNo !== undefined || params.fileNo !== "") {
            fileNo = params.fileNo;
        }

        if (params.title === undefined || params.title === '') {
            res.json({"success": false, "message": "档案标题不能为空！"});
            return;
        }

        let page = 0;
        if (params.page !== undefined || params.page !== "") {
            page = params.page;
        }

        // if (params.beginDate === undefined || params.beginDate === '') {
        //     res.json({"success": false, "message": "文件日期不能为空！"});
        //     return;
        // }

        let storagePeriod = 0;
        if (params.storagePeriod !== undefined || params.storagePeriod !== "") {
            storagePeriod = params.storagePeriod;
        }

        let rank = 0;
        if (params.rank !== undefined || params.rank !== "") {
            rank = params.rank;
        }

        let carrier = 0;
        if (params.carrier !== undefined || params.carrier !== "") {
            carrier = params.carrier;
        }

        let text = 0;
        if (params.text !== undefined || params.text !== "") {
            text = params.text;
        }

        let recordType = 0;
        if (params.recordType !== undefined || params.recordType !== "") {
            recordType = params.recordType;
        }

        req.app.db.query("select archived from s_" + code + " where id = ? and isDelete = ?", [params.fatherId, 0], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "所属档案信息不存在，无法添加文件!"});
                return;
            }

            if (results[0].archived === 1) {
                res.json({"success": false, "message": "所属档案信息已归档，无法添加文件!"});
                return;
            }

            let keyword = getKeyword(params.title);

            req.app.db.query("call proc_archives_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [code, 1, 0, fatherId, 0, 0, '', 0, fileNo, params.fileCode,
                    params.title, params.subTitle, params.content, params.person1, params.person2, page, params.beginDate, null,
                    storagePeriod, rank, carrier, text, recordType,
                    keyword, params.archivesFrom, params.archivesTo, user.id, user.trueName], function (err, results, fields) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    let result = results[0][0]._result;

                    res.json({"success": result === 1, "message": global.archivesMsg.add[result]});
                });
        });
    }
});

/**
 * 删除档案信息 2018-10-18
 *e
 * 按id删除指定的档案信息
 */
router.delete('/:code/basearchives/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = params.code;

    if (params.id === undefined || params.id === "" || !(params.id > 0)) {
        res.json({"success": false, "message": "档案编码不正确！"});
        return;
    }

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    req.app.db.query("select archived from s_" + code + " where id = ? and isDelete = ?", [params.id, 0], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "档案、文件信息不存在，无法删除!"});
            return;
        }

        if (results[0].archived === 1) {
            res.json({"success": false, "message": "档案、文件信息已归档，无法删除!"});
            return;
        }

        req.app.db.query("call proc_archives_delete(?, ?)", [code, params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            let result = results[0][0]._result;

            res.json({"success": result === 1, "message": global.archivesMsg.del[result]});
        });
    });
});

router.post('/:code/basearchives/:id/archived', filter.authorize, function (req, res, next) {
    let params = req.body;
    let id = req.params.id;
    let code = req.params.code;

    if (id === undefined || id === "" || !(id > 0)) {
        res.json({"success": false, "message": "档案编码不正确！"});
        return;
    }

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    if (params.archivesFrom === undefined || params.archivesFrom === "") {
        res.json({"success": false, "message": "档案移交人不能为空！"});
        return;
    }

    if (params.archivesTo === undefined || params.archivesTo === "") {
        res.json({"success": false, "message": "档案接受人不能为空！"});
        return;
    }

    // if (params.archivesDate === undefined || params.archivesDate === "") {
    //     res.json({"success": false, "message": "档案归档日期不能为空！"});
    //     return;
    // }

    req.app.db.query("call proc_archives_archived(?, ?, ?, ?, ?, ?)", [code, id, 1, params.archivesFrom, params.archivesTo, new Date()], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        let result = results[0][0]._result;

        res.json({"success": result === 1, "message": global.archivesMsg.archived[result]});
    });
});

router.post('/:code/basearchives/:id/unArchived', filter.authorize, function (req, res, next) {
    let params = req.params;

    if (params.id === undefined || params.id === "" || !(params.id > 0)) {
        res.json({"success": false, "message": "档案编码不正确！"});
        return;
    }

    if (params.code === undefined || params.code === "") {
        res.json({"success": false, "message": "档案所属机构编码不正确！"});
        return;
    }

    req.app.db.query("call proc_archives_archived(?, ?, ?, ?, ?, ?)", [params.code, params.id, 0, null, null, null], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        let result = results[0][0]._result;

        res.json({"success": result === 1, "message": global.archivesMsg.archived[result]});
    });
});

function getKeyword(value) {
    let r = '';
    let arr = global.jieba.extract(value, 10);
    for (let i = 0; i < arr.length; i++) {
        r += arr[i].word + ' ';
    }
    return r;
}
module.exports = router;
    